<?php

namespace backend\widgets\Chart;

use yii\base\Widget;
use yii\data\SqlDataProvider;
use yii\helpers\Json;

class SalesOnlineOfflineWidget extends Widget
{
    public $event_id;
    private $sales;

    public function init()
    {
        $this->sales = \Yii::$app->db->createCommand('
            SELECT SUM(`tariff`) as summ, COUNT(*) as count, is_online_sale
            FROM ticket_sales 
            WHERE event_id=:event_id
            GROUP BY `is_online_sale`
        ', [':event_id' => $this->event_id])->queryAll();

        parent::init();
    }

    public function run()
    {   
        $this->registerPlugin();
        echo '<div>
              <canvas id="OnlineOfflineChart"></canvas>
          </div>';
    }

    protected function registerPlugin()
    {

        $view = $this->getView();

        ChartAsset::register($view);
        
        $jsonSales = Json::encode($this->sales);

        $view->registerJs("
            const salesOnlineOfflineCanvas = document.getElementById('OnlineOfflineChart');
            const dataOnlineOfflineSales = " . $jsonSales . ";

            for(i = 0; i < dataOnlineOfflineSales.length; i++)
            {
                if(dataOnlineOfflineSales[i].is_online_sale == 0) 
                {
                    dataOnlineOfflineSales[i].is_online_sale = 'Оффлайн';
                }
                if(dataOnlineOfflineSales[i].is_online_sale == 1) 
                {
                    dataOnlineOfflineSales[i].is_online_sale = 'Онлайн';
                }
            }

            new Chart(salesOnlineOfflineCanvas, {
                type: 'pie',
                data: {
                    labels: dataOnlineOfflineSales.map(row => row.is_online_sale),
                    datasets: [{
                        label: 'Количество билетов',
                        data: dataOnlineOfflineSales.map(row => row.count),
                        borderWidth: 1
                    }]
                },
                options: {
                  responsive: true,
                  plugins: {
                    legend: {
                      position: 'top',
                    },
                    title: {
                      display: true,
                      text: 'Распределение онлайн и офлайн продаж'
                    }
                  }
                },
            });");
        }


}
